package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;

    public TcpEchoClient(String serverIP,int port) throws IOException {
        //这个操作相当于客户端和服务器建立了 tcp 连接
        // 这里的连接连上了, 服务器的 accept 就会返回.
        socket = new Socket(serverIP,port);
    }


    public void start() throws IOException {
        //客户端从键盘上获取信息
        Scanner scanner = new Scanner(System.in);

        try(InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();) {

            //发送请求
            PrintWriter printWriter = new PrintWriter(outputStream);
            //读取响应
            Scanner scannerFromServerSocket = new Scanner(inputStream);
            while (true) {
                //从键盘上获取信息
                // 1. 从键盘上读取用户输入的内容.
                System.out.print("-> ");
                String request = scanner.next();

                // 2. 把读取的内容构造成请求, 发送给服务器.
                //    注意, 这里的发送, 是带有换行的!!
                printWriter.println(request);
                // 不要忘记刷新 flush
                printWriter.flush();

                // 3. 从服务器读取响应内容
                String response = scannerFromServerSocket.next();

                // 4. 把响应结果显示到控制台上.
                System.out.println("re: " + request + " ; " + "res: "+  response);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1",9090);
        tcpEchoClient.start();
    }
}
